"""
自定义分页组件, 使用说明:
在视图函数中
def pretty_list(request):
    # 1. 根据自己的情况筛选数据
    queryset = models.PrettyNum.objects.all()
    # 2. 实例化分页对象
    page_obj = Pagination(request, queryset)

    context = {
        # 分完页的数据
        'pre_set': page_obj.page_queryset,
        # 生成的页码
        'page_str': page_obj.html()
    }

    return render(request, 'pretty_list.html', context)

在HTML中
    {% for obj in pre_set %}
        {{ obj.xx }}
    {% endfor %}
    <ul class="pagination">
        {{ page_str }}
    </ul>

"""
from django.utils.safestring import mark_safe


class Pagination(object):
    def __init__(self, request, queryset, page_size=10, page_param='page', plus=2):
        """
        :param request: 请求对象
        :param queryset: 符合条件的数据(根据这个数据对其进行分页处理)
        :param page_size: 每页显示多少条数据
        :param page_param: 在url中传递的获取分页的参数, 如: /pretty/list?page=2
        :param plus: 显示当前页 前或后几页(页码)
        """
        import copy
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        query_dict.setlist('page', [11])
        self.query_dict = query_dict
        self.page_param = page_param

        page = request.GET.get(page_param, '1')

        if page.isdecimal():
            page = int(page)
        self.page = page
        self.page_size = page_size
        self.start = (page - 1) * page_size
        self.end = page * page_size

        self.page_queryset = queryset[self.start:self.end]

        # 数据库总条数
        total_count = queryset.count()

        # 总页码
        total_page_count, div = divmod(total_count, page_size)
        if div:
            total_page_count += 1
        total_page_count = max(total_page_count, 1)

        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        # 计算出显示当前页的前2页和后2页
        if self.total_page_count <= 2 * self.plus + 1:
            # 数据库中数据比较少
            start_page = 1
            end_page = self.total_page_count
        else:
            # 数据库中数据很多
            # 当前页小于plus时, 小极值
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            else:
                # 当前页>plus
                if self.page + self.plus > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus
        # 页码
        # 首页

        self.query_dict.setlist(self.page_param, [1])

        page_str_list = [f'<li><a href="?{self.query_dict.urlencode()}">首页</a></li>']

        # 上一页
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = f'<li><a href="?{self.query_dict.urlencode()}">上一页</a></li>'
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = f'<li><a href="?{self.query_dict.urlencode()}">上一页</a></li>'
        page_str_list.append(prev)

        for i in range(start_page, end_page + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = f'<li class="active"><a href="?{self.query_dict.urlencode()}">{i}</a></li>'
            else:
                ele = f'<li><a href="?{self.query_dict.urlencode()}">{i}</a></li>'
            page_str_list.append(ele)

        # 下一页
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            prev = f'<li><a href="?{self.query_dict.urlencode()}">下一页</a></li>'
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            prev = f'<li><a href="?{self.query_dict.urlencode()}">下一页</a></li>'
        page_str_list.append(prev)
        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_list.append(f'<li><a href="?{self.query_dict.urlencode()}">尾页</a></li>')

        # 搜索框
        search_string = """
        <li>
            <form method="get" style="float: left;margin-left: -1px;display: inline-block;width: 80px;border-radius: 0">
                <div class="input-group" style="width: 200px">
                    <input type="text" name="page" class="form-control" placeholder="页码">
                    <span class="input-group-btn">
                        <button class="btn btn-default" style="border-radius: 0" type="submit">跳转</button>
                    </span>
                </div>
            </form>
        </li>
        """
        page_str_list.append(search_string)

        # 标记为安全
        page_str = mark_safe(''.join(page_str_list))
        return page_str
